/*
  Programa GEFE - Gestión de eventos lúdicos.
  Copyright (C) 2010  Antonio Ramírez Marti

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "dialogopales.h"
#include "ui_dialogopales.h"
#include <QDateTime>

dialogoPales::dialogoPales(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::dialogoPales)
{
    ui->setupUi(this);
    setup();
}

dialogoPales::~dialogoPales()
{
    delete listaPales;
    delete ui;
}

void dialogoPales::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void dialogoPales::setup()
{
    listaPales=0;
    creaModelo();
    rellenaComboBox();
    conectaAcciones();
}

void dialogoPales::creaModelo()
{
    if(listaPales)
    {
        delete listaPales;
        listaPales=0;
    }

    listaPales=new QSqlQueryModel(this);

    {
        QSqlQuery query(QSqlDatabase::database("evento"));

        query.exec("SELECT producto,count(*) from pales group by producto");

        listaPales->setQuery(query);
    }

    ui->vistaPales->setModel(listaPales);
    listaPales->setHeaderData(0,Qt::Horizontal,"Producto");
    listaPales->setHeaderData(1,Qt::Horizontal,"Pales abiertos");
    ui->vistaPales->resizeColumnsToContents();

}

void dialogoPales::rellenaComboBox()
{
    ui->productosComboBox->clear();
    {
        QSqlQuery query(QSqlDatabase::database("evento"));

        query.exec("SELECT DISTINCT nombre FROM producto");

        while(query.next())
            ui->productosComboBox->addItem(query.value(0).toString());
    }
}

void dialogoPales::conectaAcciones()
{
    connect(ui->abrirButton,SIGNAL(clicked()),this,SLOT(abrePale()));
}

void dialogoPales::abrePale()
{
    QString timestamp=QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss ap");

    {
        QSqlQuery query(QSqlDatabase::database("evento"));

        query.prepare("INSERT INTO pales(producto,timestamp) VALUES(:nombre,:time)");
        query.bindValue(":nombre",ui->productosComboBox->currentText());
        query.bindValue(":time",timestamp);

        query.exec();
    }

    reloadListaPales();
}

void dialogoPales::reloadListaPales()
{
    QSqlQuery query=listaPales->query();

    query.exec();

    listaPales->setQuery(query);
    ui->vistaPales->resizeColumnsToContents();
}
